<template>
  <a-modal width="99%" :visible="visible" :confirmLoading="confirmLoading"
           :okButtonProps="{ style: { display: 'none' } }" @cancel="handleCancel" cancelText="关闭" style="top:20px;">
    <section slot="title" style="display: flex;">
      <span>{{ '查看订单-' + (model.orderType == 1 ? '特殊订单' : '普通订单') }}</span>
      <span style="color: #1890FF;margin-left: 20px;">当前订单状态：{{ model.status_dictText }}</span>
      <div class="operate-buttons">
        <a-popconfirm title="确定取消吗?" v-if="model.status == 0" placement="topLeft" v-has="'order:cancel'"
                      @confirm="() => handleCancelOrder()">
          <a-button size="small" :loading="loadingC" type="danger" ghost>取消订单</a-button>
        </a-popconfirm>

        <a-popconfirm title="确定删除吗?" placement="topLeft" v-if="[0, 4, 8].includes(model.status)"
                      v-has="'order:delete'" @confirm="() => handleRepeal()">
          <a-button size="small" :loading="loadingD" type="danger" ghost style="margin-left: 15px">删除订单</a-button>
        </a-popconfirm>

        <a-popconfirm title="确定反审核吗?" v-else-if="model.status == 1" v-has="'order:contraryApprove'"
                      placement="topLeft" @confirm="() => handleAnti(1)">
          <a-button size="small" :loading="loadingA" type="danger" ghost>反审核</a-button>
        </a-popconfirm>
        <a-popconfirm title="确定撤销初审吗?" v-else-if="model.status == 5" v-has="'order:cancelApprove'"
                      placement="topLeft" @confirm="() => handleAnti(0)">
          <a-button size="small" :loading="loadingA" type="danger" ghost>撤销初审</a-button>
        </a-popconfirm>
        <a-popconfirm title="确定撤销结案吗?" v-else-if="model.status == 3" v-has="'order:revokeCloseOrder'"
                      placement="topLeft" @confirm="() => handleRevokeClose()">
          <a-button size="small" :loading="loadingA" type="danger" ghost>撤销结案</a-button>
        </a-popconfirm>


        <a-button size="small" v-show="model.status === 0 && model.payStatus === 4" style="margin-left: 15px"
                  @click="handleConfirm" :loading="loadingS">订单确认
        </a-button>
        <!-- <span class="color-danger" v-show="model.creditAuthorizeFlag == 1">授信订单</span> -->
        <a-button size="small" style="margin-left: 15px" @click="$emit('handleTrace', model)">订单跟踪</a-button>
      </div>
    </section>
    <div class="title">基本信息</div>
    <a-descriptions title="" bordered size="small" :column="4">
      <a-descriptions-item label="订单编号">
        {{ model.orderNo }}
      </a-descriptions-item>
      <a-descriptions-item label="用户编号">
        {{ model.memberId }}
      </a-descriptions-item>
      <a-descriptions-item label="下单时间">
        {{ model.createTime }}
      </a-descriptions-item>
      <a-descriptions-item label="发货时间">
        {{ model.deliveryTime }}
      </a-descriptions-item>
      <a-descriptions-item label="物流公司">
        {{ model.deliveryCompany }}
      </a-descriptions-item>
      <a-descriptions-item label="物流单号">
        {{ model.deliverySn }}
      </a-descriptions-item>
      <a-descriptions-item label="经销商">
        {{ model.storeId_dictText }}
      </a-descriptions-item>
      <a-descriptions-item label="可用余额">
        {{ discountData.balance }}
      </a-descriptions-item>
      <a-descriptions-item label="收货人">
        {{ model.receiverName }}
      </a-descriptions-item>
      <a-descriptions-item label="收货电话">
        {{ model.receiverPhone }}
      </a-descriptions-item>
      <a-descriptions-item label="收货地">
        {{ model.receiverProvince }} - {{ model.receiverCity }} - {{ model.receiverRegion }}-
        {{ model.town }}
      </a-descriptions-item>
      <a-descriptions-item label="详细地址">
        {{ model.receiverDetailAddress }}
      </a-descriptions-item>
      <a-descriptions-item label="订单备注" :span="4">
        {{ model.note }}
      </a-descriptions-item>
    </a-descriptions>
    <div class="title">商品信息</div>
    <a-table style="margin-bottom: 24px;font-size: 12px;" rowKey="id" bordered :scroll="{ x: 800 }"
             :columns="goodsColumns" ref="table" class="minTable" :pagination="false" :dataSource="goodsData"
             size="small">
      <template slot="footer">
        <a-table size="small" :columns="goodsColumns" :showHeader="false" :dataSource="footerDataSource"
                 :scroll="{ x: 800 }" rowKey="id" class="footerTable" :pagination="false"
                 style="font-size: 12px;">
        </a-table>
      </template>
    </a-table>
    <!-- <oms-order-process-memo-modal ref="OmsOrderProcessMemoModal" /> -->
  </a-modal>

</template>

<script>
import {httpAction, putAction, postAction, getAction} from '@/api/manage'
import DetailList from '@/components/tools/DetailList'
import ABadge from "ant-design-vue/es/badge/Badge"
import OmsOrderProcessMemoModal from './OmsOrderProcessMemoModal';
import {fixedTwo,fixedThree} from '@/utils/util';

const DetailListItem = DetailList.Item

export default {
  name: "OmsOrderViewModalJX",
  components: {
    ABadge,
    DetailList,
    DetailListItem,
    OmsOrderProcessMemoModal
  },
  data() {
    return {
      visible: false,
      confirmLoading: false,
      model: {},
      url: {
        omsOrderItem: {
          list: '/oms/omsOrder/queryOmsOrderItemByMainId'
        },
        omsOrderInvoice: {
          list: '/oms/omsOrder/queryOmsOrderInvoiceByMainId'
        },
        storeInfo: "stm/stmStoreInfo/storeInfo",
        confirmBatch: '/oms/omsOrder/confirmBatch',
        cancel: '/oms/omsOrder/cancel',
        repeal: '/oms/omsOrder/remove',
        anti: '/oms/omsOrder/antiApprove',
        revokeClose: '/oms/omsOrder/revokeClose',
      },
      discountData:
        {
          id: 1,
          balance: 0,
        },
      goodsColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 36,
          align: 'center',
          customRender: (t, r, index) => {
            return t.id == 'heji' ? '-' : (Number(index) + 1)
          }
        },
        {
          title: "物料编码",
          key: "productSkuCode",
          width: 110,
          align: "center",
          dataIndex: "productSkuCode",
        },
        {
          title: "物料名称",
          key: "productName",
          align: "center",
          width: 180,
          dataIndex: "productName",
        },
        {
          title: "单价",
          align: "center",
          key: "minUnitPrice",
          width: 60,
          dataIndex: "minUnitPrice",
        },

        {
          title: "箱价",
          align: "center",
          key: "productPrice",
          width: 70,
          dataIndex: "productPrice",
        },
        {
          title: "需求数量",
          align: "center",
          key: "minUnitQuantity",
          width: 60,
          dataIndex: "minUnitQuantity",
        },
        {
          title: "需求箱数",
          align: "center",
          key: "boxNum",
          width: 60,
          dataIndex: "boxNum",
        },
        {
          title: "分配数量",
          align: "center",
          dataIndex: "sendProQty",
          width: 60,
          // scopedSlots: { customRender: "sendProQty" },
        },
        {
          title: "分配箱数",
          align: "center",
          key: "sendQty",
          width: 60,
          dataIndex: "sendQty",
        },
        {
          title: "总金额",
          align: "center",
          width: 80,
          dataIndex: "totalProductAmount",
        },
        {
          title: "优惠金额",
          align: "center",
          width: 80,
          dataIndex: "discountAmount",
        },
        {
          title: "应付金额",
          align: "center",
          key: "needPayAmount",
          width: 80,
          dataIndex: "needPayAmount",
        },
        {
          title: "货物优惠" +
            "\n" +
            "折扣率%",
          width: 70,
          align: "center",
          dataIndex: "productDiscountRate",
        },
        {
          title: "货物优惠" +
            "\n" +
            "折扣额",
          width: 70,
          align: "center",
          dataIndex: "productDiscountAmount",
        },
        {
          title: "促销费用" +
            "\n" +
            "折扣率%",
          width: 70,
          align: "center",
          dataIndex: "promotionDiscountRate",
        },
        {
          title: "促销费用" +
            "\n" +
            "折扣额",
          width: 70,
          align: "center",
          dataIndex: "promotionDiscountAmount",
        },
        {
          title: "任务完成" +
            "\n" +
            "折扣率%",
          width: 70,
          align: "center",
          dataIndex: "missionDiscountRate",
        },
        {
          title: "任务完成" +
            "\n" +
            "折扣额",
          width: 70,
          align: "center",
          dataIndex: "missionDiscountAmount",
        },
        {
          title: "调价补差" +
            "\n" +
            "折扣率%",
          width: 70,
          align: "center",
          dataIndex: "adjustDiscountRate",
        },
        {
          title: "调价补差" +
            "\n" +
            "折扣额",
          width: 70,
          align: "center",
          dataIndex: "adjustDiscountAmount",
        },
        {
          title: "产品固定" +
            "\n" +
            "折扣率%",
          width: 70,
          align: "center",
          dataIndex: "fixedDiscountRate",
        },
        {
          title: "产品固定" +
            "\n" +
            "折扣额",
          width: 70,
          align: "center",
          dataIndex: "fixedDiscountAmount",
        },
      ],
      goodsData: [],
      loadingA: false,
      loadingC: false,
      loadingD: false,
      loadingS: false,
    }
  },
  created() {
  },
  computed: {
    // 合计
    footerDataSource() {
      let minUnitQuantity = 0, boxNum = 0, sendProQty = 0, sendQty = 0, totalRealAmount = 0, totalProductAmount = 0,
        discountAmount = 0,
        needPayAmount = 0, fixedDiscountAmount = 0, productDiscountAmount = 0,
        promotionDiscountAmount = 0, missionDiscountAmount = 0, adjustDiscountAmount = 0;
      this.goodsData.forEach(x => {
        minUnitQuantity += x.minUnitQuantity;
        boxNum += x.boxNum;
        sendProQty += x.sendProQty;
        sendQty += x.sendQty;
        totalRealAmount += Number(x.totalRealAmount);
        totalProductAmount += Number(x.totalProductAmount);
        discountAmount += Number(x.discountAmount);
        needPayAmount += Number(x.needPayAmount);
        fixedDiscountAmount += Number(x.fixedDiscountAmount);
        productDiscountAmount += Number(x.productDiscountAmount);
        promotionDiscountAmount += Number(x.promotionDiscountAmount);
        missionDiscountAmount += Number(x.missionDiscountAmount);
        adjustDiscountAmount += Number(x.adjustDiscountAmount);
      })
      return [{
        id: 'heji',
        productSkuCode: `合计${this.goodsData.length}行`,
        minUnitQuantity,
        boxNum: fixedThree(boxNum),
        sendProQty,
        sendQty: fixedThree(sendQty),
        totalRealAmount: fixedTwo(totalRealAmount),
        totalProductAmount: fixedTwo(totalProductAmount),
        discountAmount: fixedTwo(discountAmount),
        needPayAmount: fixedTwo(needPayAmount),
        fixedDiscountAmount: fixedTwo(fixedDiscountAmount),
        productDiscountAmount: fixedTwo(productDiscountAmount),
        promotionDiscountAmount: fixedTwo(promotionDiscountAmount),
        missionDiscountAmount: fixedTwo(missionDiscountAmount),
        adjustDiscountAmount: fixedTwo(adjustDiscountAmount)
      }]
    }
  },
  methods: {

    show(record) {
      console.log(record);
      this.visible = true;
      this.model = Object.assign({}, record);
      this.goodsData = [];
      // 加载子表数据
      if (this.model.id) {
        this.loadGoodsData();
        this.getStoreInfo(record.storeId);
      }
    },
    close() {
      this.$emit('close');
      this.visible = false;
    },
    loadGoodsData() {
      var params = {id: this.model.id};
      this.loading = true;
      getAction(this.url.omsOrderItem.list, params).then((res) => {
        if (res.success) {
          this.goodsData = res.result.map(x => ({
            ...x,
            needPayAmount: (x.totalRealAmount),
            boxNum: fixedThree(x.minUnitQuantity / x.productSkuSpec),
            sendQty: fixedThree(x.sendProQty / x.productSkuSpec)
          }));

          // 监听滚动条变化
          this.$nextTick(() => {
            const dom = this.$refs.table.$el.querySelectorAll('.ant-table-body')[0]
            dom.addEventListener("scroll", () => {
              this.$refs.table.$el.querySelectorAll('.ant-table-body')[1].scrollLeft = dom.scrollLeft
            }, true)
          })
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false;
      })
    },

    handleCancel() {
      this.close()
    },
    handleProcessMemo() {
      this.$refs.OmsOrderProcessMemoModal.show(this.model);
    },
    getStoreInfo(storeId) {
      let param = {};
      getAction(`${this.url.storeInfo}/${storeId}/${this.model.id}`, param).then(res => {
        if (res.success) {
          this.creditLimit = res.result.creditLimit;
          this.remainCreditLimit = res.result.remainCreditLimit;
          this.usedCreditLimit = res.result.usedCreditLimit;

          const {balance} = res.result.dealerDiscount

          this.discountData =
            {
              id: 1,
              balance
            }
        } else {
          console.log(res.message)
        }
      })
    },
    handleConfirm() {
      if (this.model.payStatus !== 4 || this.model.status !== 0) {
        this.$message.warning('确认订单只允许选择已支付并且未确认的订单！')
        return
      }
      var ids = [this.model.id]
      var that = this
      this.$confirm({
        title: '确认订单',
        content: '是否确认选中的订单?',
        onOk: function () {
          that.loadingS = true
          postAction(that.url.confirmBatch, ids).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.model.status = 1;
              that.model.status_dictText = "已确认";
              that.$emit('ok');
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.loadingS = false
          })
        }
      })
    },
    // 取消
    handleCancelOrder() {
      this.loadingC = true;
      if (this.model.status === 1 || this.model.status === 0 || this.model.status === 6 || this.model.status === 7
        || this.model.status === 9 || this.model.status === 10) {
        this.loadingC = false;
        httpAction(this.url.cancel, {id: this.model.id}, 'put').then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.model.status = 4;
            this.model.status_dictText = "已作废";
          } else {
            this.$message.warning(res.message)
          }
        })
      } else {
        this.$message.warning('订单：' + this.model.id + ' 当前已不可取消')
      }
    },
    // 删除
    handleRepeal() {
      this.loadingD = true;
      httpAction(this.url.repeal, {id: this.model.id}, 'put').then((res) => {
        this.loadingD = false;
        if (res.success) {
          this.$message.success(res.message);
          this.visible = false;
          setTimeout(() => {
            this.$emit('ok');
          }, 300)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 反审核
    handleAnti(status = 0) {
      this.loadingA = true;
      httpAction(this.url.anti, {id: this.model.id, status}, 'put').then((res) => {
        this.loadingA = false;
        if (res.success) {
          this.$message.success(res.message);
          this.visible = false;
          setTimeout(() => {
            this.$emit('ok');
          }, 300)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleRevokeClose() {
      //this.loadingA = true;
      let param = {};
      getAction(this.url.revokeClose + "/" + this.model.id, param).then((res) => {
        //this.loadingA = false;
        if (res.success) {
          this.$message.success(res.message);
          this.visible = false;
          setTimeout(() => {
            this.$emit('ok');
          }, 300)
        } else {
          this.$message.warning(res.message)
        }
      });
    },
  }
}
</script>

<style lang="less" scoped>
.operate-buttons {
  margin-left: auto;
  margin-right: 20px;
}

/deep/ .ant-modal-body {
  padding-top: 0;
}

.title {
  margin: 10px 0;
  color: rgba(0, 0, 0, 0.85);
  font-weight: bold;
  font-size: 16px;
}

.ant-modal-footer {
  padding: 10px 16px;
  text-align: right;
  border-top: 1px solid #e8e8e8;
  border-radius: 0 0 4px 4px;
  display: none;
}

/deep/ .ant-table {
  font-size: 12px;
}

.minTable {

  /deep/ .ant-table {
    th,
    td {
      padding-left: 2px !important;
      padding-right: 2px !important;
    }
  }

  /deep/ .ant-table-column-title {
    white-space: pre;
  }

  .red {
    color: red;
    font-weight: 600;
  }
}

/deep/ .ant-table-footer {
  padding: 0 !important;
}

.footerTable {

  /deep/ .ant-table-body {
    overflow-x: hidden !important;
  }

}
</style>
